/**
 * 
 */
package ro.dta.idbi.ui;

import java.awt.Color;

import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Element;

/**
 * Text area with line numbering
 * 
 * @author Tudor Dobrila
 * 
 */
public class LineTextArea extends JScrollPane {

	private static final long serialVersionUID = 6491784176010886411L;

	/**
	 * Text area containing the actual text
	 */
	private JTextArea textArea;

	/**
	 * Line text area class constructor
	 */
	public LineTextArea() {
		this(0, 0);
	}

	/**
	 * Line text area class constructor
	 * 
	 * @param rows
	 *            Initial number of rows in the text area
	 * @param columns
	 *            Initial number of columns in the text area
	 */
	public LineTextArea(int rows, int columns) {
		final JTextArea lineArea = new JTextArea("1    ");
		lineArea.setEditable(false);
		lineArea.setBackground(Color.LIGHT_GRAY);

		textArea = new JTextArea(rows, columns);
		textArea.getDocument().addDocumentListener(new DocumentListener() {
			public String getText() {
				int caretPosition = textArea.getDocument().getLength();
				Element root = textArea.getDocument().getDefaultRootElement();
				String text = "1    " + System.getProperty("line.separator");
				for (int i = 2; i < root.getElementIndex(caretPosition) + 2; i++) {
					text += i + System.getProperty("line.separator");
				}
				return text;
			}

			@Override
			public void removeUpdate(DocumentEvent e) {
				lineArea.setText(getText());

			}

			@Override
			public void insertUpdate(DocumentEvent e) {
				lineArea.setText(getText());

			}

			@Override
			public void changedUpdate(DocumentEvent e) {
				lineArea.setText(getText());
			}
		});

		getViewport().add(textArea);
		setRowHeaderView(lineArea);
		setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
	}

	/**
	 * @return Text area containing the actual text
	 */
	public JTextArea getTextArea() {
		return textArea;
	}

	/**
	 * @param textArea
	 *            New text area containing the actual text
	 */
	public void setTextArea(JTextArea textArea) {
		this.textArea = textArea;
	}

}
